package com.joelaws.prototype.client;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.form.VType;
import com.gwtext.client.widgets.layout.AnchorLayout;
import com.joelaws.prototype.client.data.User;
import com.joelaws.prototype.client.rpc.Manage;
import com.joelaws.prototype.client.rpc.ManageAsync;

public class RegisterPanel extends CenterPanel {

	public RegisterPanel() {
		setBorder(false);
		setFrame(true);
		setLayout(new AnchorLayout());
		add(getViewPanel());
	}

	private Panel getViewPanel() {

		FormPanel panel = new FormPanel();
		panel.setWidth(400);
		final TextField firstName = new TextField("First Name", "first", 230);
		firstName.setAllowBlank(false);
		panel.add(firstName);

		final TextField lastName = new TextField("Last Name", "last", 230);
		panel.add(lastName);

		final TextField email = new TextField("Email", "email", 230);
		email.setVtype(VType.EMAIL);
		panel.add(email);

		final TextField password = new TextField("Password", "password", 230);
		password.setPassword(true);
		panel.add(password);

		Button register = new Button("Register", new ButtonListenerAdapter() {

			public void onClick(Button button, EventObject e) {
				if (email.getText().equals("") || password.getText().equals("") || firstName.getText().equals("")
						|| lastName.getText().equals("")) {
					return;
				}
				ManageAsync instance = Manage.Util.getInstance();

				instance.register(email.getText(), firstName.getText(), lastName.getText(), password.getText(),
						new AsyncCallback<User>() {

							public void onFailure(Throwable error) {
								Window.alert("Error occured:" + error.toString());
							}

							public void onSuccess(User user) {
								ScreenManager.instance().setLoggedIn(user);
								System.out.println("Registered " + user.getEmail());
							}
						});
			}
		});
		panel.addButton(register);

		return panel;
	}

	public String getName() {
		return "register";
	}

}
